import * as XLSX from 'xlsx'

const ExcelUtils = {
  /**
     * 解析 Excel 文件并返回数据
     * @param {File} file - 上传的 Excel 文件
     * @returns {Promise<Object>} - 返回一个包含表头和表格数据的 Promise 对象
     */
  parseExcelFile (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()

      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })

          // 获取第一个表
          const sheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[sheetName]

          // 将表格数据转换为 JSON
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

          if (jsonData.length) {
            const headers = jsonData[0]
            const tableData = jsonData.slice(1).map((row) => {
              const rowData = {}
              headers.forEach((header, index) => {
                rowData[header] = row[index] || ''
              })
              return rowData
            })

            resolve({ headers, tableData })
          } else {
            resolve({ headers: [], tableData: [] })
          }
        } catch (error) {
          reject(error)
        }
      }

      reader.onerror = (error) => {
        reject(error)
      }
      reader.readAsArrayBuffer(file)
    })
  },
  /**
   * 解析 .dat 文件内容为对象数组
   * @param {File} file - .dat 文件
   * @returns {Promise<Object>} - 返回一个包含数据的 Promise 对象
   */
  parseDatFile (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = function (e) {
        try {
          const text = e.target.result
          const rows = text.trim().split('\n').filter(row => !row.includes('===='))
          const separatorIndex = rows.findIndex(line => line.includes('THE FINAL RESULTS:'))
          const part1 = rows.slice(0, separatorIndex).filter(row => row.trim() !== '')
          const part2 = rows.slice(separatorIndex + 1).filter(row => row.trim() !== '')
          const experimentHeaders = part1[0].split(/\s+/).filter(header => header !== '')
          const experimentData = part1.slice(1).map(row => {
            const values = row.split(/\s+/).filter(value => value !== '')
            return experimentHeaders.reduce((obj, header, index) => {
              obj[header] = values[index]
              return obj
            }, {})
          })
          const resultHeaders = part2[0].split(/\s+/).filter(header => header !== '')
          const resultData = part2.slice(1).map(row => {
            const values = row.split(/\s+/).filter(value => value !== '')
            return resultHeaders.reduce((obj, header, index) => {
              obj[header] = values[index]
              return obj
            }, {})
          })
          resolve({ experimentData, resultData })
        } catch (error) {
          reject(error)
        }
      }
      reader.onerror = (error) => {
        reject(error)
      }
      reader.readAsText(file)
    })
  },
  parseTxtFile (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = function (e) {
        try {
          const text = e.target.result
          const rows = text.trim().split('\n')
          console.log(rows)
          const results = []
          let currentFlightMach = null
          const variables = rows[3].trim().split(';')
          console.log(variables)
          const txtType = rows[0].trim()
          console.log(txtType)
          if (txtType === 'A') {
            for (let i = 3; i < rows.length; i++) {
              const line = rows[i].trim()
              if (!line.includes('\t')) {
                // New block's initial value (flight_mach_number)
                currentFlightMach = line
              } else {
                const values = line.split('\t')

                // Create a new object and dynamically add properties
                const resultObject = {
                  [variables[0]]: currentFlightMach // flight_mach_number
                }

                // Add the rest of the properties based on variables
                for (let j = 1; j < variables.length; j++) {
                  resultObject[variables[j]] = values[j - 1]
                }
                // Push the object to results array
                results.push(resultObject)
              }
            }
          }
          if (txtType === 'B') {
            for (let i = 4; i < rows.length; i++) {
              const line = rows[i].trim()
              if (!line.includes('\t')) {
                // New block's initial value (flight_mach_number)
                currentFlightMach = line
              } else {
                const values = line.split('\t')
                // Create a new object and dynamically add properties
                const resultObject = {

                }

                // Add the rest of the properties based on variables
                for (let j = 0; j < variables.length; j++) {
                  resultObject[variables[j]] = values[j]
                }
                // Push the object to results array
                results.push(resultObject)
              }
            }
          }
          resolve(results)
        } catch (error) {
          reject(error)
        }
      }
      reader.onerror = (error) => {
        reject(error)
      }
      reader.readAsText(file)
    })
  },
  commonFile () {
    return new Promise((resolve, reject) => {
      resolve()
    })
  }
}

export default ExcelUtils
